package cc.mcyx.ychat.fillter

import cc.mcyx.ychat.execution.MessageException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import javax.servlet.http.HttpServletResponse

@RestControllerAdvice
class GlobalFilter {

    @ExceptionHandler(Throwable::class)
    fun handleException(response: HttpServletResponse, ex: Exception): ResponseEntity<Map<String, Any>> {
        val body: HashMap<String, Any> = hashMapOf()
        ex.printStackTrace()
        val code: Int = when (ex) {
            is MessageException -> ex.statusCode
            else -> 500
        }
        var exMsg = ex.message ?: "Internal Server Error"
        if (ex is BindException) {
            exMsg = ex.bindingResult.allErrors[0].defaultMessage?.toString() ?: ex.message ?: "Internal Server Error"
        }
        return ResponseEntity(body.also {
            body["code"] = code
            body["message"] = exMsg
        }, HttpStatus.valueOf(code))
    }
}